package io.babystar.common.utils;


import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class ExcelUtil {

    public static void export(List<Map<String, Object>> list, LinkedHashMap<String, String> fieldMap, String filName,
                              HttpServletResponse response) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        //新建sheet
        HSSFSheet sheet = wb.createSheet(filName + "1");
        HSSFCellStyle contextstyle = wb.createCellStyle();
        HSSFRow row = null;
        int rowIndex = 0;
        row = sheet.createRow(0);
        //设置行高
        row.setHeight((short) (22.50 * 20));
        // 定义存放英文字段名和中文字段名的数组
        String[] enFields = new String[fieldMap.size()];
        String[] cnFields = new String[fieldMap.size()];
        // 填充数组
        int count = 0;
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            enFields[count] = entry.getKey();
            cnFields[count] = entry.getValue();
            count++;
        }
        //设置表头
        for (int i = 0; i < cnFields.length; i++) {
            row.createCell(i).setCellValue(cnFields[i]);
        }
        for (int i = 0; i < list.size(); i++) {
            if (rowIndex > 65535) {
                sheet = wb.createSheet(filName + "2");
                row = sheet.createRow(0);
                //设置行高
                row.setHeight((short) (22.50 * 20));
                //设置表头
                for (int k = 0; k < cnFields.length; k++) {
                    row.createCell(k).setCellValue(cnFields[k]);
                }
            }
            row = sheet.createRow(i + 1);
            for (int j = 0; j < enFields.length; j++) {
                //获取第i行第j列所放数据
                Object data = list.get(i).get(enFields[j]);
                HSSFCell contentCell = row.createCell(j);
                boolean isNum = false;
                boolean isInteger = false;
                if (data != null || "".equals(data)) {
                    //判断data是否为数值型
                    isNum = data.toString().matches("^(-?\\d+)(\\.\\d+)?$");
                    //判断data是否为整数（小数部分是否为0）
                    isInteger = data.toString().matches("^[-\\+]?[\\d]*$");
                }
                if (isNum) {
                    //HSSFDataFormat df = wb.createDataFormat(); // 此处设置数据格式
                    if (isInteger) {
                        //数据格式只显示整数
                        contextstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
                        // 设置单元格内容为double类型
                        contentCell.setCellValue(data.toString());
                    } else {
                        //保留两位小数点
                        contextstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
                        // 设置单元格内容为double类型
                        contentCell.setCellValue(Double.parseDouble(data.toString()));
                        // 设置单元格格式
                        contentCell.setCellStyle(contextstyle);
                    }
                } else {
                    if(("signTime".equals(enFields[j]) || "zjSignTime".equals(enFields[j])) && list.get(i).get(enFields[j]) != null){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        contentCell.setCellValue(sdf.format(list.get(i).get(enFields[j])));
                    }else{
                        contentCell.setCellValue(list.get(i).get(enFields[j]) == null ? "" : list.get(i).get(enFields[j]).toString());
                    }
                }
            }
            rowIndex++;
        }
        // 遍历集合数据，产生数据行
        sheet.setDefaultRowHeight((short) (16.5 * 20));
        //列宽自适应
        for (int i = 0; i <= 13; i++) {
            sheet.autoSizeColumn(i);
            //sheet.setColumnWidth(i, 252*35+323);
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //默认Excel名称
        response.setHeader("Content-disposition", "attachment;filename=balancelog.xls");
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }
}
